<template>
	<div>
		<el-card>
			<div class="system-user-search mb15">
				<el-form :model="state.param.param" label-width="120"  ref="queryFormRef" @keyup.enter.native="loadList">
					<el-row>
						<el-col :span="8">
								<el-form-item label="编号" prop="classCode">
									<el-input  v-model="state.param.param.classCode" clearable/>
								</el-form-item>
						</el-col>
						<el-col :span="8">
								<el-form-item label="名称" prop="className">
									<el-input  v-model="state.param.param.className" clearable/>
								</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
		</el-card>
		<el-card>
			<div class="btnStyle">
				<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
				<el-button type="primary" icon="ele-Edit" @click="updateHandle" :disabled="state.dataListSelections.length !== 1">修改</el-button>
				<el-button type="danger" icon="ele-Delete" @click="deleteHandle" :disabled="state.dataListSelections.length <= 0">删除</el-button>
			</div>
			<el-table :data="state.dataList" @selection-change="selectionChangeHandle" stripe style="width: 100%" v-loading="state.listLoading">
				<el-table-column prop="id" type="selection" header-align="center" align="center" width="50"/>
				<el-table-column prop="classCode" header-align="center" align="center" label="类型编码"/>
				<el-table-column prop="className" header-align="center" align="center" label="类型名称"/>
				<el-table-column prop="dataCode" header-align="center" align="center" label="键值"/>
				<el-table-column prop="dataName" header-align="center" align="center" label="名称"/>
				<el-table-column prop="dataOrder" header-align="center" align="center" label="排序"/>
				<el-table-column prop="state" header-align="center" align="center" label="状态" :formatter="formatStatus"/>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
						<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
						<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.param.page"
				background
				v-model:page-size="state.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-card>
		<el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="state.addOrUpdateVisible" :destroy-on-close='true'>
			<el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit" label-width="120px">
				<el-form-item label="类型编号" prop="classCode">
					<el-input v-model="state.submitForm.classCode" placeholder="类型编号" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item label="类型名称" prop="className">
					<el-input v-model="state.submitForm.className" placeholder="类型名称" maxlength="50"></el-input>
				</el-form-item>
				<el-form-item label="键值" prop="dataCode">
					<el-input v-model="state.submitForm.dataCode" placeholder="键值" maxlength="50"></el-input>
				</el-form-item>
				<el-form-item label="名称" prop="dataName">
					<el-input v-model="state.submitForm.dataName" placeholder="名称" maxlength="50"></el-input>
				</el-form-item>
				<el-form-item label="排序" prop="dataOrder">
					<el-input v-model="state.submitForm.dataOrder" placeholder="排序" :maxlength="4" :min="1" :max="9999" :step="1" type="number"/>
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<DicSelect v-model="state.submitForm.state" placeholder="请选择" dicCode="1001" :excludeIsKey="['100103']" style="width:100%"></DicSelect>
				</el-form-item>
				<el-form-item label="上级字典" prop="parentName">
					<el-input placeholder="请选择上级字典" v-model="state.submitForm.parentName" :disabled="true">
						<template #append>
							<el-button icon="ele-Search" @click="parentSearch()" />
						</template>
					</el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="选择上级字典" width="40%" v-model="state.visibleSelect">
			<el-form :model="state.paramSelect.param" :inline="true" ref="querySelectFormRef">
				<el-row>
					<el-col :span="8">
							<el-form-item label="编号" prop="classCode">
								<el-input  v-model="state.paramSelect.param.classCode" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
							<el-form-item label="名称" prop="className">
								<el-input  v-model="state.paramSelect.param.className" clearable/>
							</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-button type="primary" class="ml7" @click="loadListSelect">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetFormSelect(querySelectFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
			<el-table :data="state.dataListSelect" stripe style="width: 100%">
				<el-table-column prop="classCode" header-align="center" align="center" label="类型编码"/>
				<el-table-column prop="className" header-align="center" align="center" label="类型名称"/>
				<el-table-column prop="dataCode" header-align="center" align="center" label="键值"/>
				<el-table-column prop="dataName" header-align="center" align="center" label="名称"/>
				<el-table-column prop="dataOrder" header-align="center" align="center" label="排序"/>
				<el-table-column prop="state" header-align="center" align="center" label="状态" :formatter="formatStatus"/>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
						<el-button type="primary" link @click="selectParent(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onSelectSizeChange"
				@current-change="onSelectCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.paramSelect.page"
				background
				v-model:page-size="state.paramSelect.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.totalSelect">
			</el-pagination>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="dic">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { systemApi } from '/@/api/sys/system-api'
const queryFormRef = ref<FormInstance>()
const querySelectFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>();
const state = reactive({
	listLoading: false,
	listSelectLoading: false,
	dataList: [],
	dataListSelect: [],
	dataDictionaryList: {} as any,
	dataListSelections: [],
	total: 0,
	totalSelect: 0,
	param: {
		page: 1,
		pageSize: 10,
		param: {
			classCode: '',
			className: ''
		}
	},
	paramSelect: {
		page: 1,
		pageSize: 10,
		param: {
			classCode: '',
			className: ''
		}
	},
	addOrUpdateVisible: false,
	visibleSelect: false,
	submitForm: {
		id: '',
		classCode: '',
		className: '',
		dataCode: '',
		dataName: '',
		dataOrder: '',
		state: '',
		parentId: '',
		parentName: ''
	},
	submitFormRule: {
		classCode: [{ required: true, message: '类型编码不能为空', trigger: 'blur' }],
		className: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
		dataCode: [{ required: true, message: '键值不能为空', trigger: 'blur' }],
		dataName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
		dataOrder: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
		state: [{ required: true, message: '状态不能为空', trigger: 'change' }]
	},
	fill: true
})

//查询
const loadList = () => {
	state.listLoading = true
	systemApi.queryDicListByPage(state.param).then(data => {
		if (data && data.code === 0) {
			state.dataList = data.data.records
			state.total = data.data.totalRow
		} else {
			state.dataList = []
			state.total = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.listLoading = false
	})	
}
// 页面加载时
onMounted(() => {
	// 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['1001'])
	// 列表查询
	loadList()
})

const loadListSelect = () => {
	state.listSelectLoading = true
	systemApi.queryDicListByPage(state.paramSelect).then(data => {
		if (data && data.code === 0) {
			state.dataListSelect = data.data.records
			state.totalSelect = data.data.totalRow
		} else {
			state.dataListSelect = []
			state.totalSelect = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.listSelectLoading = false
	})	
}
//重置
const reSetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.param.page = 1
	loadList()
}
//重置
const reSetFormSelect = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.resetFields()
	state.paramSelect.page = 1
	loadListSelect()
}
const selectionChangeHandle = (val:any) => {
	state.dataListSelections = val
}
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.param.page = val;
	loadList()
}
// 分页改变
const onSelectSizeChange = (val: number) => {
	state.paramSelect.pageSize = val;
	loadListSelect()
}
// 分页改变
const onSelectCurrentChange = (val: number) => {
	state.paramSelect.page = val;
	loadListSelect()
}

const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList['1001'].get(cellValue);
		}
	}
}
//打开新增弹窗
const addOrUpdateHandle = () => {
	state.submitForm = {
		id: '',
		classCode: '',
		className: '',
		dataCode: '',
		dataName: '',
		dataOrder: '',
		state: '',
		parentId: '',
		parentName: ''
	}
	state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
	state.submitForm = {
		id: '',
		classCode: '',
		className: '',
		dataCode: '',
		dataName: '',
		dataOrder: '',
		state: '',
		parentId: '',
		parentName: ''
	}
	let selectId = ''
	if(!row){
		selectId = state.dataListSelections[0].id
		state.submitForm = state.dataListSelections[0]
	} else {
		state.submitForm = row
		selectId = row.id
	}
	systemApi.getDicInfoById(selectId).then(data => {
		if (data && data.code === 0) {
			state.submitForm = data.data
		}
				})
	state.addOrUpdateVisible = true
	
}
//打开删除弹窗
const deleteHandle = (id: string | undefined) => {
	var ids = id ? [id] : state.dataListSelections.map(item => {
		return item.id
	})
	if (!ids) {
		ElMessage.error('请选择记录！')
		return
	}
	ElMessageBox.confirm('是否确定删除所选记录', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		systemApi.deleteDic(ids).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('删除成功')
				loadList();
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error("删除失败")
		})
	})
}

const parentSearch = () => {
	loadListSelect()
	state.visibleSelect = true
}

const selectParent = (row: any | undefined) => {
	state.submitForm.parentId = row.id
	state.submitForm.parentName = row.className + '/' + row.dataName
	state.visibleSelect = false
}

const dataFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return
	formEl.validate((valid: boolean) => {
		if (valid) {
			// 提交数据
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			if(!state.submitForm.id) {
				// 新增
				systemApi.addDic(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			} else{
				systemApi.updateDic(state.submitForm).then((data) => {
					if (data && data.code === 0) {
						ElMessage.success('保存成功')
						// 列表查询
						loadList()
						state.addOrUpdateVisible = false
					} else {
						ElMessage.error(data.message)
					}
				}).catch(() => {
					ElMessage.error('保存失败')
				}).finally(() => {
					loading.close()
				})
			}
		}
	})
}
</script>